package com.shiro.test.javase;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.authz.permission.WildcardPermissionResolver;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;


public class ShiroIniTest2Jdbc {
    //JdbcRealm
    public static void main(String[] args) {
        DefaultSecurityManager securityManager =new DefaultSecurityManager();
        ModularRealmAuthenticator authenticator=new ModularRealmAuthenticator();
        authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        securityManager.setAuthenticator(authenticator);

        ModularRealmAuthorizer authorizer =new ModularRealmAuthorizer();
        authorizer.setPermissionResolver(new WildcardPermissionResolver());
        securityManager.setAuthenticator(authenticator);
        //dataSource=org.springframework.jdbc.datasource.DriverManagerDataSource
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        //dataSource.driverClassName=com.mysql.jdbc.Driver
        //dataSource.url=jdbc:mysql://127.0.0.1:3306/shiro_test
        //dataSource.username=root
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/shiro_test");
        dataSource.setUsername("root");
        dataSource.setPassword("");
        JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
        MyRealm2 myRealm2=new MyRealm2();
        myRealm2.setJdbcTemplate(jdbcTemplate);
        securityManager.setRealm(myRealm2);
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject =SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("admin@shiro.com","admin");
        try {
            subject.login(token);
            System.out.println("登陆成功");
            System.out.println(subject.hasRole("test"));
        } catch (AuthenticationException e) {
            //e.printStackTrace();
            System.out.println("用户名或密码错误，登录失败");
        }
    }
}
